package com.imarec.web.statistics;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.imarec.web.persistence.dao.ImageDAO;
import com.imarec.web.persistence.entities.ImageAttributeEntity;
import com.imarec.web.persistence.entities.ImageEntity;
import com.projektio.io.ImageAttribute;
import com.projektio.io.ImageTranslationService;

public class BatchSearchEngine 
{
	public static final int pixelTolerance = 75;
	public static final int colorTolerance = 15;
	public static final int imageAttributesTolerance = 40;
	
	private static final ImageTranslationService translationService = new ImageTranslationService();
	private static ImageDAO imageDAO = new ImageDAO();
	
	private static  Logger logger = Logger.getLogger(BatchSearchEngine.class);
	
	public static List<ImageEntity> getMatchingImages(File photoFile)
	{
		List<ImageEntity> photoList = null;
		
		try 
		{
			ImageAttribute[] patternAttributes = translationService.calculateImageAttributes(new FileInputStream(photoFile));
			Map<ImageAttribute, List<ImageAttributeEntity>> matchingAttributes = new HashMap<ImageAttribute, List<ImageAttributeEntity>>();
			
			for(ImageAttribute attr : patternAttributes)
			{
				matchingAttributes.put(attr, imageDAO.getMatchingAttributes(attr.getWhitePixels(), pixelTolerance, attr.getColor()[0], attr.getColor()[1], attr.getColor()[2], colorTolerance));
				
				//logger.warn(Arrays.toString(attr.getColor()));
				//matchingAttributes.put(attr, imageDAO.getMatchingAttributesForColor(attr.getColor()[0], attr.getColor()[1], attr.getColor()[2], colorTolerance));
				
			}

			//logger.warn("Pattern attributes count: " + patternAttributes.length);
			
			Map<Long, Integer> matchedImagesCount = new HashMap<Long, Integer>();	
			List<Long> countedImages = new ArrayList<Long>();
			for(Map.Entry<ImageAttribute, List<ImageAttributeEntity>> entry : matchingAttributes.entrySet())
			{
				countedImages.clear();
				
				for(ImageAttributeEntity attribute : entry.getValue())
				{
					if(!countedImages.contains(attribute.getImage().getId()))
					{
						if(matchedImagesCount.containsKey(attribute.getImage().getId()))
						{
							matchedImagesCount.put(attribute.getImage().getId(), matchedImagesCount.get(attribute.getImage().getId()) + 1);							
						}
						else
						{
							matchedImagesCount.put(attribute.getImage().getId(), 1);
						}
						
						countedImages.add(attribute.getImage().getId());
					}
					
				}
			}
			
			//logger.warn("Matching images map: " + matchedImagesCount.toString());
			
			photoList = new ArrayList<ImageEntity>();
			for(Map.Entry<Long, Integer> entry : matchedImagesCount.entrySet())
			{
				if((100.0 * entry.getValue() / patternAttributes.length) >= imageAttributesTolerance)
				{
					photoList.add(imageDAO.getImageByID(entry.getKey()));
				}
			}
			
		}
		catch(Exception exc)
		{
			exc.printStackTrace();
		}
		
		return photoList;
	}
	
	public static void main(String... args) throws Exception
	{
		String dir = "D:/Documents/Various items/Imarec-mini/200x200_MATRIX";
		String logDir = "D:/imarec_log-S-"+pixelTolerance+"-"+colorTolerance+"-"+imageAttributesTolerance+".txt";
		
		String smallPatternSuffix = "_S";
		String largePatternSuffix = "_M";
		
		PrintWriter logWriter = new PrintWriter(new FileWriter(new File(logDir)));
		
		int filesFound = 0;
		int totalFiles = 0;
		
		for(File file : new File(dir).listFiles())
		{
			if(file.isFile() && file.getName().matches(".*\\.(bmp||BMP)"))
			{
				totalFiles++;
				
				boolean imageFound = false;
				List<ImageEntity> matchingFiles = getMatchingImages(file);
				
				for(ImageEntity image : matchingFiles)
				{
					if((file.getName().equalsIgnoreCase(image.getTitle() + smallPatternSuffix + ".bmp"))||(file.getName().equalsIgnoreCase(image.getTitle() + largePatternSuffix + ".bmp")))
					{
						imageFound = true;
						filesFound++;
						break;
					}
				}
				
				logWriter.println(file.getName() + "\t" + matchingFiles.size() + "\t" + imageFound);
			}
			System.out.println(totalFiles);
		}
		
		logWriter.println("Total images found: " + filesFound + "/" + totalFiles);
		
		logWriter.close();
	}
}
